#include "Thread.h"
#include "Thread.h"
#include "Thread.h"
#include "Thread.h"
#include "Thread.h"
#include <stdio.h>

//定义一个__thread的变量
__thread const char *name = "current_thread";

Thread::Thread(ThreadCallback &&cb, const string &name1)
: _thid(0)
, _name(name1)
, _isRunning(false)
, _cb(std::move(cb))
{
}

Thread::~Thread()
{
}

void Thread::start()
{
    int ret = pthread_create(&_thid, nullptr, threadFunc, this);
    if(ret)
    {
        perror("pthread_create");
        return;
    }

    _isRunning = true;
}

void Thread::stop()
{
    if(_isRunning)
    {
        int ret = pthread_join(_thid, nullptr);
        if(ret)
        {
            perror("pthread_join");
            return;
        }
        _isRunning = false;
    }
}

void *Thread::threadFunc(void *arg)
{
    Thread *pth = static_cast<Thread *>(arg);
    //注意这个代码===============================
    name = pth->_name.c_str();//从string转换为const char *
    //==========================================
    
    if(pth)
    {
        pth->_cb();//回调函数
    }

    pthread_exit(nullptr);
}
